package com.group3.admin.servlet;

import java.io.IOException;

import javax.jms.JMSException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.group3.admin.producer.Producer;
import com.group3.admin.service.IAMerchantService;
import com.group3.admin.service.impl.AMerchantServiceImpl;
import com.group3.entity.AMerchant;


/**
 * Servlet implementation class BlockServlet
 */
//@WebServlet("/BlockServlet")
public class BlockServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	IAMerchantService iAMerchantService = new AMerchantServiceImpl();
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public BlockServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String mId = request.getParameter("mId");
		System.out.println("BlockServlet : Merchant chagned BlackList status : " + mId);
		
		// 从数据库获取 mId
		
		AMerchant aMerchant = iAMerchantService.queryAMerchantByMId(mId);
		// 对黑名单状态的改变是取值后取反 white <--> black 
		String status = "WHITE".equals(aMerchant.getStatus()) ? "BLACK" : "WHITE";
		System.out.println("BlockServlet : new status for mId " + mId + " : " + status);
		aMerchant.setStatus(status);
		AMerchant aMerchant2 = iAMerchantService.updateStatusByType(aMerchant) ;
		Producer producer = new Producer();
		try {			
			producer.tellMBlock(aMerchant2);
			System.out.println("process tellMBlock is "+aMerchant2);
		} catch (JMSException e) {
			e.printStackTrace();
		}
		// 更新黑名单状态
		String new_status = "";
		if (aMerchant2== null) {
			new_status = null;
			System.out.println("BlockServlet : update failed!");
		} else {
			new_status = "success";
			System.out.println("BlockServlet : update successfully!");
		}
//		request.getRequestDispatcher("MListServlet").forward(request, response);
		response.setContentType("application/json;charset=utf-8");
		String jsonString = JSON.toJSONString(new_status, true);
		response.getWriter().append(jsonString);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
